package edu.ynu.se.xiecheng.achitectureclass.service;

import com.aliyun.oss.OSS;
import edu.ynu.se.xiecheng.achitectureclass.config.OssConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
@RequiredArgsConstructor
public class OssService {
    private final OSS ossClient;
    private final OssConfig ossConfig;
    
    public String uploadImage(String imageUrl, String prefix) {
        try {
            // 从萤石云下载图片
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();
            
            // 生成OSS中的文件名
            String fileName = generateFileName(prefix);
            
            // 上传到OSS
            ossClient.putObject(ossConfig.getBucketName(), fileName, inputStream);
            
            // 返回可访问的URL
            return ossConfig.getUrlPrefix() + "/" + fileName;
            
        } catch (Exception e) {
            log.error("上传图片到OSS失败", e);
            throw new RuntimeException("上传图片到OSS失败: " + e.getMessage());
        }
    }
    
    private String generateFileName(String prefix) {
        LocalDateTime now = LocalDateTime.now();
        String yearMonth = now.format(DateTimeFormatter.ofPattern("yyyy/MM"));
        String dateTime = now.format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        // 目录结构: greenhouse/camera_captures/年/月/文件名
        return String.format("greenhouse/%s/%s/%s_%s.jpg", 
            prefix,           // camera_captures
            yearMonth,        // 2024/01
            dateTime,         // 20240105_123456
            System.nanoTime() // 确保文件名唯一
        );
    }
} 